import base64
import json
import urllib
import io

import requests


class BdTextRecognition:
    def __init__(self):
        self.client_id = "yPACBpFqsJjCgnu8Ym3ib46o"
        self.client_secret = "7fXznVJs1tDXRCi56jn5JaAzkm5LOsUp"

    def main(self,path):
        url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token=" + self.get_access_token()

        # image 可以通过 get_file_content_as_base64("C:\fakepath\包装食品营养表.jpg",True) 方法获取
        payload = f'image={self.get_file_content_as_base64(path,True)}&detect_direction=false&paragraph=false&probability=false&multidirectional_recognize=false'
        headers = {
            'Accept': 'application/json'
        }

        response = requests.request("POST", url, headers=headers, data=payload.encode("utf-8"))

        print("百度文本识别结果",response.text)
        return response.text

    def get_file_content_as_base64(self,path, urlencoded=False):
        """
        获取文件base64编码
        :param path: 文件路径
        :param urlencoded: 是否对结果进行urlencoded
        :return: base64编码信息
        """
        with open(path, "rb") as f:
            content = base64.b64encode(f.read()).decode("utf8")
            if urlencoded:
                content = urllib.parse.quote_plus(content)
        return content

    def get_access_token(self):
        """
        使用 AK，SK 生成鉴权签名（Access Token）
        :return: access_token，或是None(如果错误)
        """
        url = "https://aip.baidubce.com/oauth/2.0/token"
        params = {"grant_type": "client_credentials", "client_id": self.client_id, "client_secret": self.client_secret}
        return str(requests.post(url, params=params).json().get("access_token"))


text_recognition = BdTextRecognition()